package com.shouer.doc.application.presenter;

import android.content.Context;
import android.net.Uri;
import android.util.Log;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.shouer.doc.ShouerAppContext;
import com.shouer.doc.application.response.QueryUserResponse;
import com.shouer.doc.common.ShouerConst;
import com.shouer.doc.common.util.DateFormatUtil;
import com.shouer.doc.common.util.FileUtil;
import com.shouer.doc.gsonadapter.DoubleDefault0Adapter;
import com.shouer.doc.gsonadapter.IntegerDefault0Adapter;
import com.shouer.doc.gsonadapter.LongDefault0Adapter;
import com.shouer.doc.request.BaseResponse;
import com.shouer.doc.request.GsonRequest;
import com.shouer.doc.request.RequestUtil;
import com.shouer.doc.ui.conversation.response.QueryCovOrderResponse;
import com.shouer.doc.ui.login.model.DoctorInfoModel;
import com.shouer.doc.ui.login.model.UserModel;
import com.shouer.doc.ui.neworder.model.SimpleOrderModel;

import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import io.rong.imkit.RongIM;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.UserInfo;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * Created by yangyayun on 2017/2/21.
 */

public class AppPresenterImpl implements IAppPresenter{

    private Context context;

    public AppPresenterImpl(Context context)
    {
        this.context=context;
    }


    @Override
    public Group getGroupInfoByGroupId(String orderId) {

        OkHttpClient client = RequestUtil.getOkHttpClient(context);

        Map<String, String> param = new HashMap<>();
        param.put("orderId", orderId);
        JSONObject postParamObject = new JSONObject(param);
        String timeStamp = DateFormatUtil.getCurrentSystemDateByBreakCharacter("");
        String header = RequestUtil.genHeader(timeStamp, "queryOrder");
        String postString = RequestUtil.encryptMessage(timeStamp, header, postParamObject.toString());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/text; charset=utf-8"), postString);

        Request request = new Request.Builder().url(ShouerConst.APP_SERVER_https).post(requestBody).build();
        try {
            okhttp3.Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) {
                return null;
            } else {
                Gson mGson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().enableComplexMapKeySerialization() //支持Map的key为复杂对象的形式
                        .serializeNulls().setDateFormat("yyyy-MM-dd HH:mm:ss:SSS")//时间转化为特定格式
                        .registerTypeAdapter(Integer.class, new IntegerDefault0Adapter())
                        .registerTypeAdapter(int.class, new IntegerDefault0Adapter())
                        .registerTypeAdapter(Double.class, new DoubleDefault0Adapter())
                        .registerTypeAdapter(double.class, new DoubleDefault0Adapter())
                        .registerTypeAdapter(Long.class, new LongDefault0Adapter())
                        .registerTypeAdapter(long.class, new LongDefault0Adapter())
                        .setPrettyPrinting() //对json结果格式化.
                        .setVersion(1.0).create();
                QueryCovOrderResponse queryCovOrderResponse = mGson.fromJson(response.body().charStream(), QueryCovOrderResponse.class);
                Log.i(ShouerAppContext.class.getSimpleName(),queryCovOrderResponse.toString());
                if (queryCovOrderResponse.getErrorCode() >= 0) {
                    if (null != queryCovOrderResponse.getOrderInfoList() && queryCovOrderResponse.getOrderInfoList().size() > 0) {

                        SimpleOrderModel orderModel = queryCovOrderResponse.getOrderInfoList().get(0);
                        Group group = new Group(orderId, orderModel.getPatient().getPatName(), Uri.parse(FileUtil.connectFilePath(ShouerConst.RES_SERVER,orderModel.getDoctor().getDocImageUrl())));
                        return group;
                    }

                } else {
                    return null;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();

            return null;
        }
        return null;
    }

    @Override
    public UserInfo getUserInfoByUserId(String userId) {

        OkHttpClient client = RequestUtil.getOkHttpClient(context);
        Map<String, String> param = new HashMap<>();
        param.put("userId", userId);
        JSONObject postParamObject = new JSONObject(param);
        String timeStamp = DateFormatUtil.getCurrentSystemDateByBreakCharacter("");
        String header = RequestUtil.genHeader(timeStamp, "queryUser");
        String postString = RequestUtil.encryptMessage(timeStamp, header, postParamObject.toString());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/text; charset=utf-8"), postString);

        Request request = new Request.Builder().url(ShouerConst.APP_SERVER_https).post(requestBody).build();
        try {
            okhttp3.Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) {
                return null;
            } else {
                Gson mGson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().enableComplexMapKeySerialization() //支持Map的key为复杂对象的形式
                        .serializeNulls().setDateFormat("yyyy-MM-dd HH:mm:ss:SSS")//时间转化为特定格式
                        .registerTypeAdapter(Integer.class, new IntegerDefault0Adapter())
                        .registerTypeAdapter(int.class, new IntegerDefault0Adapter())
                        .registerTypeAdapter(Double.class, new DoubleDefault0Adapter())
                        .registerTypeAdapter(double.class, new DoubleDefault0Adapter())
                        .registerTypeAdapter(Long.class, new LongDefault0Adapter())
                        .registerTypeAdapter(long.class, new LongDefault0Adapter())
                        .setPrettyPrinting() //对json结果格式化.
                        .setVersion(1.0).create();
                QueryUserResponse queryCovOrderResponse = mGson.fromJson(response.body().charStream(), QueryUserResponse.class);
                Log.i(ShouerAppContext.class.getSimpleName(),queryCovOrderResponse.toString());
                if (queryCovOrderResponse.getErrorCode() >= 0) {
                    if (null!=queryCovOrderResponse.getDoctor())
                    {
                        DoctorInfoModel docModel=queryCovOrderResponse.getDoctor();
                        UserInfo userInfo=new UserInfo(docModel.getDocId(),docModel.getDocName(), Uri.parse(FileUtil.connectFilePath(ShouerConst.RES_SERVER,docModel.getDocImageUrl())));
                        RongIM.getInstance().refreshUserInfoCache(userInfo);
                    }else if (null!=queryCovOrderResponse.getUser())
                    {
                        UserModel userModel=queryCovOrderResponse.getUser();
                        UserInfo userInfo=new UserInfo(userModel.getUserId(),userModel.getUserName(), Uri.parse(FileUtil.connectFilePath(ShouerConst.RES_SERVER,"")));
                        RongIM.getInstance().refreshUserInfoCache(userInfo);
                    }

                } else {
                    return null;
                }
            }
        } catch (IOException e) {
            Log.e(AppPresenterImpl.class.getSimpleName(),e.getMessage());
            return null;
        }
        return null;

    }

    @Override
    public void logout(String userId) {
        Map<String, String> param = new HashMap<>();
        param.put("userId", userId);

        final GsonRequest<BaseResponse> request = new GsonRequest(ShouerConst.APP_SERVER_https,"logout", BaseResponse.class, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });

        RequestUtil.sendRequest(context, param, request);
    }
}
